<script setup lang="ts">
import { uploadImageAPI } from '@/apis/consult'
import type { Image } from '@/types/consult'
import { showLoadingToast, showToast, type UploaderAfterRead } from 'vant'
import { ref } from 'vue'

// 接收父组件提交过来的数据
defineProps<{
  disabled?: boolean
}>()

// 定义响应式数据 来收集用户输入的数据
const message = ref('')
// 3.3+: 可选的、更简洁的语法
const emit = defineEmits<{
  'send-msg': [msg: string]
  'send-image': [img: Image]
}>()
// 发送消息
const onSendMessage = () => {
  // 判断用户是否输入了内容
  if (message.value.trim() === '') return showToast('请输入内容')
  // console.log(message.value)
  // 将收集的数据发送给父组件
  emit('send-msg', message.value)
  // 将输入框清空
  message.value = ''
}

const onAfterRead: UploaderAfterRead = async (item) => {
  // console.log(item)
  if (Array.isArray(item)) return
  if (!item.file) return
  const s = showLoadingToast({ message: '图片正在上传中', duration: 0 })
  // 调用文件上传的接口
  const res = await uploadImageAPI(item.file)
  s.close()
  // 将图片的数据提交给父组件
  emit('send-image', res.data)
}
</script>

<template>
  <div class="room-action">
    <van-field
      type="text"
      class="input"
      :border="false"
      placeholder="问医生"
      autocomplete="off"
      :disabled="disabled"
      v-model="message"
      @keydown.enter="onSendMessage"
    ></van-field>
    <van-uploader
      :preview-image="false"
      :disabled="disabled"
      :after-read="onAfterRead"
    >
      <cp-icon name="consult-img" />
    </van-uploader>
  </div>
</template>

<style lang="scss" scoped>
.room-action {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 60px;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 1;
  box-sizing: border-box;
  .input {
    background-color: var(--cp-bg);
    border: none;
    border-radius: 25px;
    margin-right: 10px;
    padding: 8px 15px;
  }
  .cp-icon {
    width: 24px;
    height: 24px;
  }
}
</style>
